﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MyStack.Models;

namespace MyStack.Controllers
{
	[HandleError]
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			ViewData["Message"] = "Welcome myStack!";

			MyStackRepository db = new MyStackRepository();

			StoriesView latestStory = db.GetLatestStory();

			ViewData["latest"] = latestStory;

			if (User.Identity.IsAuthenticated)
			{
				return RedirectToAction("Explore", "Story");
			}
			else
			{
				return View();
			}			
		}

		public ActionResult About()
		{
			return View();
		}

        public ActionResult Mail()
        {
            return View("Mail");
        }


		[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Mail(FormCollection formValues)
        {
            MailView mail_view = new MailView();
            UpdateModel<MailView>(mail_view);
             
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();


            String user_info = "\n\nNo User Information available";

            if (User.Identity.Name != "" )
            {
                MyStackRepository db = new MyStackRepository();
                int user_id = db.GetUserIdByName(User.Identity.Name);
                User user = db.GetUser(user_id);
                user_info = "\n\nUser name: " + user.Name.Trim() + 
                            "\nUser id: " + user.UserId + 
                            "\nUser email: " + user.Email.Trim();
            }
            // Godaddy does not allow From field to have user email address (to avoid spoofing)
            msg.From = new System.Net.Mail.MailAddress("feedback@stacktheweb.com");
            msg.To.Add(new System.Net.Mail.MailAddress("feedback@stacktheweb.com"));
            msg.Subject = mail_view.Subject;
            msg.Body = mail_view.Body + user_info;
            smtp.Send(msg);

            return View("Thanks");
        }
	}
}
